<template>
  <div class="section_common">
    <div class="main">
      <el-form ref="form" label-width="100px">

        <el-form-item label="区域" required>
          <el-radio-group v-model="area" disabled  @change="changeArea">
            <el-radio  label="深圳">深圳</el-radio>
            <el-radio  label="合肥">合肥</el-radio>
            <el-radio  label="武汉">武汉</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="所属地点" required>
          <el-select v-model="place" :filterable="true" size="mini" placeholder="请选择" @change="changePlace">
            <el-option v-for="(item,index) in placeField" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="使用人工号">
          <el-input v-model="jobNumId" size="mini" @change="findUser($event)"></el-input>
        </el-form-item>
        <el-form-item label="使用人">
          <el-input v-model="uname" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader
            size="mini"
            ref="refHandle"
            v-model="dept"
            :options="depts"
            :clearable="true"
            @change="deptChange"
            :props="{ checkStrictly: true }"
            filterable
          ></el-cascader>
        </el-form-item>

        <el-form-item label="领用物品" required><!--multiple-->
          <el-select v-model="items" :filterable="true" size="mini" placeholder="请选择" @change="selectItem">
            <el-option v-for="(item,index) in itemsField" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="领用物品">
          <el-input v-model="items" size="mini" readonly @focus="showItems = true"></el-input>
          <van-popup v-model="showItems" position="bottom">
            <van-picker
                    show-toolbar
                    :columns="itemsField"
                    @confirm="selectItem"
                    @cancel="showItems = false"
            />
          </van-popup>
        </el-form-item>-->
        <el-form-item label="使用类型">
          <el-radio v-model="classification" label="个人">个人</el-radio>
          <el-radio v-model="classification" label="公共">公共</el-radio>
        </el-form-item>
        <el-form-item label="领用数量">
          <el-input v-model="number" size="mini" @change="checkNumber"></el-input>
<!--&&          <el-button plain size="mini" type="warning" v-show="remainshow">库存：{{remain}}</el-button>-->
        </el-form-item>
        <el-form-item label="申请类型">
          <!--<el-select v-model="applytype" size="mini" placeholder="请选择">
            <el-option label="新增物品" value="新增物品"></el-option>
            <el-option label="已坏物品" value="已坏物品"></el-option>
          </el-select>-->
          <el-radio v-model="applytype" label="新增物品">新增物品</el-radio>
          <el-radio v-model="applytype" label="已坏物品">已坏物品</el-radio>
        </el-form-item>
        <el-form-item label="用途/更换原因">
          <el-input type="textarea" v-model="reason" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <!--<el-upload
            action="#"
            class="upload-demo"
            :on-change="handleChange"
            :file-list="fileList"
            :multiple="false"
            :limit="1"
            list-type
          >
            <el-button size="mini" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip"></div>
          </el-upload>-->
          <input id="file" class="file-upload-input" ref="inputer" type="file" accept="*/*" @change="afterRead()">
        </el-form-item>


        <div class="upload_area">
          <van-steps direction="vertical" :active="active" active-icon="checked" active-color="#38f">
            <van-step v-show="oneShow">
              <p style="font-size:16px;font-weight: 900">指定审批人</p>
              <van-image v-for="(item,index) in ywusers" :key="index" :src="item.avatar" width="60" height="60" style="margin-right: 20px;margin-bottom: 20px"><p style="font-size: 10px ;justify-content: center">{{item.name}}</p></van-image>
            </van-step>
            <van-step>
              <p style="font-size:16px;font-weight: 900">行政组</p>
              <van-image v-for="(item,index) in spusers" :key="index" :src="item.avatar" width="60" height="60" style="margin-right: 20px;margin-bottom: 20px"><p style="font-size: 10px ;justify-content: center">{{item.name}}</p></van-image>
            </van-step>
            <van-step v-if="threeShow">
              <van-image v-for="(item,index) in thrusers" :key="index" :src="item.avatar" width="60" height="60" style="margin-right: 20px;margin-bottom: 20px"><p style="font-size: 10px ;justify-content: center">{{item.name}}</p></van-image>
            </van-step>
          </van-steps>
        </div>


        <el-form-item>
          <el-button type="primary" size="mini" @click="submitPost" v-bind:disabled="isSubmitShow"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue';
  import { Image as VanImage ,Dialog,Toast,Picker,Popup} from 'vant';
  Vue.use(Picker);
  Vue.use(Popup);
  Vue.use(VanImage);
  Vue.use(Dialog)
export default {
  data() {
    return {
      area:"",
      place:"",
      placeField:[],
      uname:"",
      deptId:"",
//      deptName:"",//部门名称
      jobNumId:"",
      items:"",//领用物品
      reason:"",
      number:"",
      remain:"",//选择物品的剩余数量
      applytype:"新增物品",
      classification:"个人",
      active:"-1",//步骤索引,从0开始
      code:"",

      nowUser: '',
      title: "物品领用申请",
      fileList: [{fileId:""}],
      fileName:"",
      fileUrl:"",
      addArticlesApply: '/mobiles/addArticlesApply',
      uploadImageUrl: '/mobiles/uploadFile',
      showItems:false,
      itemsField:[],
      itemsList:[],
      remainshow:false,

      isSubmit:"提交",
      isSubmitShow:false,
      spusers:[],//对应的行政组审批用户

      oneShow:false,//第一层审批是否显示
      ywusers:[],//指定审批人
      threeShow:false,//主要是针对武汉有主管二级审批
      thrusers:[],

      //fileList: [],
      dept: [],
      depts: [],
    };
  },

  created() {
    this.nowUser=JSON.parse(localStorage.getItem('userInfo')).userId;
    var jobnumid=JSON.parse(localStorage.getItem('userInfo')).jobNumId;
    if (jobnumid.indexOf("HF")!=-1){
      this.area="合肥"
    }else if (jobnumid.indexOf("WH")!=-1){
      this.area="武汉"
    }else {
      this.area="深圳"
    }
    this.getAllPlace();
    //this.getAreas();//获取资产管理中现存的所有区域
    this.jobNumId=JSON.parse(localStorage.getItem('userInfo')).jobNumId;
    this.uname=JSON.parse(localStorage.getItem('userInfo')).name;
    this.dept=JSON.parse(localStorage.getItem('userInfo')).deptId;
    this.deptId=this.dept;
    this.selXZUser();//查找所有审批者
    this.selDept();//初始化部门选择
    //this.getAllItems();//初始化可选择的物品
  },

  methods: {
    getAllPlace(){
      this.$https.post('/mobiles/selInventoryPlace',{
        nowUser:this.nowUser,
        area:this.area
      }).then((res)=>{
        this.placeField=[];
        this.formatArea(res.data,this.placeField);
      }).catch(err => {
        console.log(err);
      })
    },
    changeArea(value){
      this.area=value;
      this.place=" ";
      this.items="";
      this.getAllPlace();
    },

    changePlace(value){
      this.place=value;
      this.items="";
      this.getAllItems();
    },

    //选择审批人，即行政组所有人,初始化显示数据，在选择完地区后会在改变getAllItems
    selXZUser(){
      this.$https.post('/mobiles/selApplyUser',{
        nowUser:this.nowUser
      }).then((res)=>{
        //debugger
        this.spusers=res.data.spusers;//相应地区的行政组人员
        this.ywusers=res.data.ywusers;//相应地区的一级审批人员（运维人员）
        if (res.data.thrusers){
          this.threeShow=true;
          this.thrusers=res.data.thrusers;
        }

      }).catch(err => {
        console.log(err);
      })
    },

    //找到“运维-深圳”的审批人
    /*selywUser(){
      this.$https.post('/mobiles/selUsherByDept',{
        deptName:"运维-深圳"
      }).then((res)=>{
        this.ywusers=res.data.data;
      }).catch(err => {
        console.log(err);
      })
    },*/

    //找到资产指定的管理者进行审批
    selArticlesManager(){
      this.$https.post('/mobiles/selArticlesManager',{
        area:this.area,
        place:this.place,
        goods:this.items,
      }).then((res)=>{
        if (res.data.data.length>0){
          this.spusers=res.data.data;
        }
      }).catch(err => {
        console.log(err);
      })
    },

    findUser(){
      this.$https.post('/mobiles/findUserByJobNum',{
        jobNum:this.jobNumId,
      }).then((res)=>{
        //console.log(res);
        if (res.data.code=='500'){
          this.code=500;
          this.$toast(res.data.message);
          this.jobNumId="";
        }else {
          this.code='';
        }
        if (res.data.code=="200"){
          this.uname=res.data.data.name;
          this.deptId=res.data.data.deptId;
          this.dept=res.data.data.deptId;
//          this.deptName=res.data.data.deptName;
          /*this.oposId=res.data.data.posId;
          this.oposName=res.data.data.posName;*/
        }

      }).catch(err=>{
        console.log(err);
      })
    },

    //初始化选择部门
    selDept(){
      this.$https.post('/mobiles/selPCDept').then((res)=>{
        //debugger
        //console.log(res.data.data)
        this.depts=this.formatCsData(res.data.data);
      }).catch(err => {
        console.log(err);
      });
    },
    //格式化级联下拉框的数据
    formatCsData(data){
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatCsData(data[i].children)
        }
      }
      return data
    },
    //点击获得选中的部门
    /*selectDept(item) {
      this.currDept = item;
      this.treeShow = false;
      this.deptName=this.currDept.name
      this.deptId=this.currDept.id
      //this.getPosById(this.currDept.id)
    },*/

    deptChange(value){
      //console.log(value)
      this.deptId=value[value.length-1];
      this.$refs.refHandle.dropDownVisible = false
    },

    formatLacation(data,curr,foo,id){
      if(data){
        console.log(foo)
        for(let i=0;i<data.length;i++){
          console.log(data[i])
          curr.push({
            label:data[i][foo],
            value:data[i][id],
          })
        }
        console.log(curr)
      }
    },
    formatArea(data,curr){
      if(data){
        for(let i=0;i<data.length;i++){
          console.log(data[i])
          curr.push({
            label:data[i],
            value:data[i],
          })
        }
        console.log(curr)
      }
    },
    //获取相关物品和审批人
    getAllItems(){
      this.itemsField=[];
      this.items="";
      this.remain="";
      this.remainshow=false;
      //console.log(id)
      this.$https.post('/mobiles/selItems',{
        area:this.area,
        place:this.place
      }).then((res)=>{
        /*this.itemsList=res.data;
        for(var i=0;i<this.itemsList.length;i++){
          this.itemsField.push(this.itemsList[i].goods);
        }*/
        this.formatLacation(res.data.items,this.itemsField,'goods','goods');

      }).catch(err => {
        console.log(err);
      })
    },

    //查找选中物品的剩余数量
/*&&    findRemain(){
      this.$https.post('/mobiles/selItemsNum',{
        area:this.area,
        items:this.items,
      }).then((res)=>{
        this.remain=res.data.remain;
        this.remainshow=true;
      }).catch(err => {
        console.log(err);
      })
    },*/
    //点击选中的物品
    selectItem(value){
      this.items=value;
      this.showItems=false;

//&&      this.findRemain();
      if (this.items.indexOf("电脑")!==-1  ||this.items.indexOf("显示器")!==-1  ||this.items.indexOf("显示屏")!==-1 || this.items.indexOf("主机")!==-1 || this.items.indexOf("键盘")!==-1 || this.items.indexOf("鼠标")!==-1 || this.items.indexOf("硬盘")!==-1 || this.items.indexOf("内存")!==-1){
        //this.selywUser();
        //debugger
        if (this.area.indexOf("武汉")!=-1){
          this.oneShow=false;
        }else {
          this.oneShow=true;
        }
        this.selArticlesManager();
      }else {
        this.oneShow=false;
        this.selArticlesManager();
      }

    },

    //检查领用数量
/*&&    checkNumber(){
      if (parseInt(this.number)>parseInt(this.remain)){
        Dialog.alert({
          message:'物品领用数量不能超过剩余数量，\n\n如需要请联系管理员',
        })
      }
    },*/


    // 返回
    goBack() {
      this.$router.go(-1);
    },
    // 提交
    submitPost() {
      if (!this.isNull()) return false;
      /*var s = '';
      s = this.getImageUrl(s);*/
      // on confirm
      this.$https.post(this.addArticlesApply, {
        nowUser:this.nowUser,
        area:this.area,
        place:this.place,
        uname:this.uname,
        jobNumId: this.jobNumId,
        deptId:this.deptId,
        items:this.items,
        number:this.number,
        applytype:this.applytype,
        classification:this.classification,
        reason: this.reason,
        fileId:this.fileList[this.fileList.length-1].fileId,
        oneShow:this.oneShow

      }).then(res => {
        res;
        Toast("推送成功");
        this.$router.go(-1);
      }).catch(err => {
        console.log(err)
      });
    },
    //判断相关数据是否为空
    isNull() {
      if (this.code=='500'){
        this.$toast("用户信息错误，请检查工号");
        return false;
      }
      if (this.area==''){
        this.$toast("区域不能为空");
        return false;
      }
      if (this.place==''){
        this.$toast("所属地点不能为空");
        return false;
      }
      if (this.jobNumId==''){
        this.$toast("使用人工号不能为空");
        return false;
      }
      if (this.uname==''){
        this.$toast("使用人不能为空");
        return false;
      }
      if (this.deptId==''){
        this.$toast("使用人部门不能为空");
        return false;
      }
      if (this.items==''){
        this.$toast("领用物品不能为空");
        return false;
      }
      if (this.number==''){
        this.$toast("领用数量不能为空");
        return false;
      }
      if (this.applytype == '') {
        this.$toast("申请类型不能为空");
        return false;
      }
/*&&      if (parseInt(this.number)>parseInt(this.remain)){
        this.$toast("物品领用数量不能超过剩余数量");
        return false;
      }*/
      return true;
    },

    //监听上传变动
    afterRead() {
      let formData = new FormData();
      //console.log(this.$refs.inputer);
      var fs=this.$refs.inputer.files;
      for (let i = 0; i < fs.length; i++) {
        formData.append("fileList", fs[i]);  //文件上传处理
      }
      this.$https.post(this.uploadImageUrl,formData,{
        timeout: 0, //无超时时间
        headers: { "Content-Type": "multipart/form-data" }
      }).then(res => {
        this.fileList=res.data.data;
        this.fileName=this.fileList[this.fileList.length-1].fileName;
        this.fileUrl=this.fileList[this.fileList.length-1].filePath;
        Toast("上传完成");
      }).catch(err => {
        console.log(err);
      })
    },


    //上传事件
    handleChange(file) {
      this.fileList = [file];

    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  display: flex;
  justify-items: center;
  margin: 0 auto;
  .el-form {
    padding-right: 10px;
    .el-form-item {
      .el-form-item__label {
        line-height: 16px;
      }
      margin-bottom: 5px;
    }
  }
}
</style>